package cn.nkpro.elcube.mq.config;

import cn.nkpro.elcube.mq.config.NkMQClientProperties;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Header;

import java.io.IOException;

@Configuration
@EnableConfigurationProperties({
        NkMQClientProperties.class
})
public class NkRabbitDemoConfig {

    /**
     * 默认交换机
     */
    @Bean
    public DirectExchange DemoExchangeDirect() {
        return new DirectExchange("amq.direct");
    }

    /**
     * 演示用死信队列
     */
    @Bean
    public Queue DemoQueueDead() {
        return new Queue("elcube.demo.dead");
    }
    /**
     * 绑定演示用死信队列
     */
    @Bean
    public Binding binding_QueueVoucherDead_ExchangeHbfDirect() {
        return BindingBuilder.bind(DemoQueueDead()).to(DemoExchangeDirect()).withQueueName();
    }

    /**
     * 演示用队列
     */
    @Bean
    public Queue DemoQueue() {
        return QueueBuilder.durable("elcube.demo")
                .deadLetterExchange("amq.direct")
                .deadLetterRoutingKey("elcube.demo.dead")
                .build();
    }
    /**
     * 绑定演示用队列
     */
    @Bean
    public Binding binding_QueueSys_ExchangeDefaultDirect() {
        return BindingBuilder.bind(DemoQueue()).to(DemoExchangeDirect()).withQueueName();
    }

    @Bean
    public DemoConsumer DemoRabbitConsumer(){
        return new DemoConsumer();
    }


    @RabbitListener(queues = "elcube.demo",ackMode = "MANUAL")
    static class DemoConsumer {
        @RabbitHandler(isDefault = true)
        public void handler(Message<String> msg, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
            System.out.println("elcube收到的消息内容为：" + msg.getPayload());
            if(Math.random()>0.5){
                System.out.println("确认");
                channel.basicAck(deliveryTag,false);//任务处理成功调用
            }else{
                System.out.println("退回");
                channel.basicReject(deliveryTag,false); //任务处理异常，需要重新执行的情况下调用
            }
        }
    }
}
